package com.hospital.hospitalsystemgateway.config;

import com.alibaba.fastjson.JSONObject;
import com.hospital.hospitalsystemgateway.modules.dto.UserExt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author qiancheng@cqxyy.net
 * @date 2023/2/21
 */
@Component
@Slf4j
public class TokenVerify implements GlobalFilter {

    @Autowired
    private NotAuthUrlProperties notAuthUrlProperties;

    //设置过期时间
    private static final long EXPIRE_DATE = 30*60*10000;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String currentUrl = exchange.getRequest().getURI().getPath();
        if (shouldSkip(currentUrl)) {
            log.info("==========已跳过url{}=====", currentUrl);
            return chain.filter(exchange);
        }
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst("token");
        //token不存在
        if (token==null || token.equals("")){
            return loginResponse(exchange,"token does not exist");
        }

        //验证token是否正确
        try {
            UserExt userExt = TokenConfig.tokenToOut(token);
            if (userExt.getOverdueTime().after(new Date())){
                return chain.filter(exchange);
            }else{
                return loginResponse(exchange,"token expired");
            }
        }catch (Exception e){
            return loginResponse(exchange,"The token is incorrect. Do not create a token by illegal means");
        }
    }

    /**
     * token验证不通过返回
     * @param exchange
     * @param error
     * @return
     */
    public static Mono<Void> loginResponse(ServerWebExchange exchange,String error) {
        Map<String,Object> resultJson = new HashMap<>();
        resultJson.put("code", 401);
        resultJson.put("message", error);
        String jsonObject = JSONObject.toJSONString(resultJson);
        ServerHttpResponse response = exchange.getResponse();
        byte[] bytes = jsonObject.getBytes();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);

        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.fromSupplier(()->buffer));
    }

    /**
     * 应该跳过的请求
     * @param currentUrl
     * @return
     */
    private boolean shouldSkip(String currentUrl) {
        PathMatcher pathMatcher = new AntPathMatcher();
        for (String skipPath : notAuthUrlProperties.getShouldSkipUrls()) {
            if (pathMatcher.match(skipPath, currentUrl)) {
                return true;
            }
        }
        return false;
    }
}
